package net.ib.mtalk.network.task;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.SetBuddyInfoRes;
import net.ib.mntalk.protocol.Session.SetSuggestionsReq;
import net.ib.mntalk.protocol.Session.SetSuggestionsRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.helper.BuddyDatabaseHelper;
import net.ib.mtalk.database.helper.SuggestionDatabaseHelper;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.util.MTalkLogWriter;

public class SetSuggestionTask extends AsyncNetTask {
	
	private SetSuggestionsReq mSetSuggestionsReq;
	private String name;

	public SetSuggestionTask(Context context, Handler uiHandler, SetSuggestionsReq setSuggestionsReq, String name) {
		super(context, uiHandler);
		this.mSetSuggestionsReq = setSuggestionsReq;
		this.name = name;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope rev = new TcpEnvelope.Builder()
		.setType(TcpEnvelope.REQUEST)
		.setMessage(mSetSuggestionsReq)
		.setMethodId(Session.Suggestion.SetSuggestions)
		.build();
	
	return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject,	Object receivedObject) {
		MTalkLogWriter.d("SetSuggestionTask.onPostExecute()");
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		SetSuggestionsRes setSuggestionsRes = (SetSuggestionsRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("SetSuggestionTask ResponseCode : " + setSuggestionsRes.getResponseCode());
		
		if(setSuggestionsRes.getResponseCode() == Common.SUCCESS){
			SuggestionDatabaseHelper.updateSuggestionStatus(mContext, mSetSuggestionsReq);
			Message msg = mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_SET_SUGGESTION_SUCCESS);
			msg.obj = name;
			mUiHandler.sendMessageAtFrontOfQueue(msg);
		} else {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_SET_SUGGESTION_FAIL));
		}
	}

}
